import os
import random
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk

import ttkthemes

frame = None
objInput = None
lines = None
objOutput = None
objCount = None


def _import():
    path = filedialog.askopenfilename(
        defaultextension='.txt',
        filetypes=[('txt', '.txt')],
        initialdir=os.getcwd(),  # 要点：用于文件浏览器，从当前运行路径开始
    )
    if path:
        try:
            with open(path, 'r', encoding='utf-8') as f:
                global lines
                lines = f.readlines()
                for i in range(len(lines)):
                    lines[i] = lines[i].strip()
                objInput.set(lines)
        except Exception as e:
            messagebox.showerror('错误！', f'导入名单失败！e={e}', parent=frame)


def _export():
    if lines:
        path = filedialog.asksaveasfilename(
            defaultextension='.txt',
            filetypes=[('txt', '.txt')],
            initialdir=os.getcwd(),
        )
        if path:
            try:
                with open(path, 'w', encoding='utf-8') as f:
                    f.write('\n'.join(lines))
            except Exception as e:
                messagebox.showerror('错误！', f'导出名单失败！e={e}', parent=frame)
    else:
        messagebox.showerror('错误！', f'还没有导入名单！', parent=frame)


def _swap(_list, i, j):
    tmp = _list[i]
    _list[i] = _list[j]
    _list[j] = tmp


def _disorder():
    if lines:
        _len = len(lines)
        for i in range(_len):
            target = int(random.random() * _len)
            _swap(lines, i, target)

        objInput.set(lines)
    else:
        messagebox.showerror('错误！', f'还没有导入名单！', parent=frame)


def _getLucky():
    if lines:
        _count = objCount.get()

        luck = list()
        for i in range(_count):
            target = int(random.random() * len(lines))
            luck.append(lines[target])

        objOutput.set(luck)
    else:
        messagebox.showerror('错误！', f'还没有导入名单！', parent=frame)


def getCurrentDir():
    defaultPath = os.path.dirname(__file__)
    if defaultPath == '':
        import sys
        defaultPath = sys.path[0]

    return defaultPath


def main():
    tk = Tk()
    tk.title('Lucky Dog (by Python)')
    tk.iconbitmap(os.path.join(getCurrentDir(), 'logo.ico'))  # 要点：解决pyinstall打包后的exe，运行时找不到资源
    tk.resizable(width=False, height=False)

    style = ttkthemes.ThemedStyle(tk)
    style.set_theme('ubuntu')

    global frame
    frame = ttk.Frame(tk)
    frame.pack()

    btnImport = Button(frame, text="名单导入", command=_import)
    btnImport.grid(row=0, column=0, columnspan=2, sticky=NSEW, ipady=30)

    btnExport = Button(frame, text="名单导出", command=_export)
    btnExport.grid(row=1, column=0, columnspan=2, sticky=NSEW, ipady=30)

    btnDisorder = Button(frame, text="名单乱序", command=_disorder)
    btnDisorder.grid(row=2, column=0, columnspan=2, sticky=NSEW, ipady=30)

    labCount = Label(frame, text="幸运数量")
    labCount.grid(row=3, column=0, sticky=NSEW, ipady=30)
    global objCount
    objCount = IntVar(value=1)
    inputCount = Entry(frame, textvariable=objCount)  # 要点：可以直接绑定变量
    inputCount.grid(row=3, column=1, sticky=NSEW, ipady=30)  # 要点：NSEW表示填满

    btnGetLocky = Button(frame, text="抽奖", command=_getLucky)
    btnGetLocky.grid(row=4, column=0, columnspan=2, sticky=NSEW, ipady=30)

    global objInput
    objInput = StringVar()
    listInput = Listbox(frame, listvariable=objInput)  # 要点：可以直接绑定变量
    listInput.grid(row=0, column=2, rowspan=5, sticky=NSEW, ipady=30)

    global objOutput
    objOutput = StringVar()
    listOutput = Listbox(frame, listvariable=objOutput)
    listOutput.grid(row=0, column=3, rowspan=5, sticky=NSEW, ipady=30)

    tk.mainloop()


if __name__ == '__main__':
    main()
